package com.liang.servlet.bill;

import com.alibaba.fastjson.JSONArray;
import com.liang.pojo.Bill;
import com.liang.pojo.Provider;
import com.liang.pojo.User;
import com.liang.service.Provider.ProviderServiceImpl;
import com.liang.service.bill.BillServiceImpl;
import com.liang.util.Constant;
import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class BillServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method.equals("query")) {
            BillQuery(req, resp);
        } else if (method.equals("add")) {
            addBill(req, resp);
        } else if (method.equals("getproviderlist")) {
            getProviderlist(req, resp);
        } else if (method.equals("view") || method.equals("modify")) {
            billView(req, resp);
        } else if (method.equals("modifysave")) {
            modifyBill(req, resp);
        } else if (method.equals("delbill")) {
            delBill(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    public static void BillQuery(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String queryProductName = req.getParameter("queryProductName");
        String queryProviderId = req.getParameter("queryProviderId");
        String queryIsPayment = req.getParameter("queryIsPayment");
        String pageIndex = req.getParameter("pageIndex");
        Integer providerId = 0;
        Integer isPayment = 0;
        int pageNo = 1;
        int pageSize = 8;
        if (!StringUtils.isNullOrEmpty(queryProviderId)) {
            providerId = Integer.parseInt(queryProviderId);
        }
        if (!StringUtils.isNullOrEmpty(queryIsPayment)) {
            isPayment = Integer.parseInt(queryIsPayment);
        }
        if (!StringUtils.isNullOrEmpty(pageIndex)) {
            pageNo = Integer.parseInt(pageIndex);
        }
//        获取供应商列表
        ProviderServiceImpl providerService = new ProviderServiceImpl();
        Integer providerTotal = providerService.getCount(null, null);//获取供应商总数
        List<Provider> providerList = providerService.getProviderList(null, null, 1, providerTotal);//获取所有供应商
        req.setAttribute("providerList", providerList);
        BillServiceImpl billService = new BillServiceImpl();
        ;
//        获取订单列表总数
        int count = billService.getCount(queryProductName, providerId, isPayment);
        int maxPage = 0;
        if (count % pageSize == 0) {
            maxPage = count / pageSize;
        } else if (count % pageSize > 0) {
            maxPage = count / pageSize + 1;
        }
        if (pageNo < 1) {
            pageNo = 1;
        } else if (pageNo > maxPage) {
            pageNo = maxPage;
        }
        List<Bill> billList = null;
        if (count > 0) {
            billList = billService.getBillList(queryProductName, providerId, isPayment, pageNo, pageSize);
        }
        req.setAttribute("totalCount", count);
        req.setAttribute("currentPageNo", pageNo);
        req.setAttribute("totalPageCount", maxPage);
        req.setAttribute("billList", billList);
        req.setAttribute("queryProductName", queryProductName);
        req.setAttribute("queryProviderId", queryProviderId);
        req.setAttribute("queryIsPayment", queryIsPayment);
        req.getRequestDispatcher("/jsp/billlist.jsp").forward(req, resp);
    }

    public static void addBill(HttpServletRequest req, HttpServletResponse resp) {
        String billCode = req.getParameter("billCode");
        String productName = req.getParameter("productName");
        String productUnit = req.getParameter("productUnit");
        String productCount = req.getParameter("productCount");
        String totalPrice = req.getParameter("totalPrice");
        String providerId = req.getParameter("providerId");
        String isPayment = req.getParameter("isPayment");
        BigDecimal count = new BigDecimal(0);
        BigDecimal total = new BigDecimal(0);
        Integer Payment = 0;
        Integer _providerId = 0;
        Bill bill = null;
        try {
            if (!StringUtils.isNullOrEmpty(productCount)) {
                count = new BigDecimal(productCount);
            }
            if (!StringUtils.isNullOrEmpty(totalPrice)) {
                total = new BigDecimal(totalPrice);
            }
            if (!StringUtils.isNullOrEmpty(providerId)) {
                _providerId = Integer.parseInt(providerId);
            }
            if (!StringUtils.isNullOrEmpty(isPayment)) {
                Payment = Integer.parseInt(isPayment);
            }

            HttpSession session = req.getSession();
            Object attribute = session.getAttribute(Constant.USER_SESSION);
            User user = (User) attribute;
            bill = new Bill();
            bill.setBillCode(billCode);
            bill.setProductName(productName);
            bill.setProductUnit(productUnit);
            bill.setProductCount(count);
            bill.setTotalPrice(total);
            bill.setProviderId(_providerId);
            bill.setIsPayment(Payment);
            bill.setCreationDate(new Date());
            bill.setCreatedBy(user.getId());
            BillServiceImpl billService = new BillServiceImpl();
            Bill billListSearch = billService.getBillListSearch(billCode, 0);
            if (billListSearch != null) {
                req.setAttribute(Constant.Message, "提交失败,订单编码已存在");
                req.getRequestDispatcher("billadd.jsp").forward(req, resp);
                return;
            }

            Boolean flag = billService.addBill(bill);

            if (flag) {
                resp.sendRedirect("bill.do?method=query");
            } else {
                req.setAttribute(Constant.Message, "提交失败");
                req.getRequestDispatcher("billadd.jsp").forward(req, resp);
            }
        } catch (IOException | ServletException e) {
            throw new RuntimeException(e);
        }


    }

    public static void getProviderlist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        ProviderServiceImpl providerService = new ProviderServiceImpl();
        Integer providerTotal = providerService.getCount(null, null);//获取供应商总数
        List<Provider> providerList = providerService.getProviderList(null, null, 1, providerTotal);//获取所有供应商
        PrintWriter writer = resp.getWriter();
        writer.println(JSONArray.toJSONString(providerList));
        writer.flush();
    }

    public static void billView(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String billid = req.getParameter("billid");
        String method = req.getParameter("method");
        Integer id = 0;
        if (!StringUtils.isNullOrEmpty(billid)) {
            id = Integer.parseInt(billid);
        }
        BillServiceImpl billService = new BillServiceImpl();
        Bill billListSearch = billService.getBillListSearch(null, id);
        req.setAttribute("bill", billListSearch);
        String url = "bill.do?method=query";
        if (method.equals("view")) {
            url = "billview.jsp";
        } else if (method.equals("modify")) {
            url = "billmodify.jsp";
        }
        req.getRequestDispatcher(url).forward(req, resp);
    }

    public static void modifyBill(HttpServletRequest req, HttpServletResponse resp) {
        String billId = req.getParameter("id");
        String billCode = req.getParameter("billCode");
        String productName = req.getParameter("productName");
        String productUnit = req.getParameter("productUnit");
        String productCount = req.getParameter("productCount");
        String totalPrice = req.getParameter("totalPrice");
        String providerId = req.getParameter("providerId");
        String isPayment = req.getParameter("isPayment");
        BigDecimal count = new BigDecimal(0);
        BigDecimal total = new BigDecimal(0);
        Integer id = 0;
        Integer Payment = 0;
        Integer _providerId = 0;
        Bill bill = null;
        try {
            if (!StringUtils.isNullOrEmpty(billId)) {
                id = Integer.parseInt(billId);
            }
            if (!StringUtils.isNullOrEmpty(productCount)) {
                count = new BigDecimal(productCount);
            }
            if (!StringUtils.isNullOrEmpty(totalPrice)) {
                total = new BigDecimal(totalPrice);
            }
            if (!StringUtils.isNullOrEmpty(providerId)) {
                _providerId = Integer.parseInt(providerId);
            }
            if (!StringUtils.isNullOrEmpty(isPayment)) {
                Payment = Integer.parseInt(isPayment);
            }

            HttpSession session = req.getSession();
            Object attribute = session.getAttribute(Constant.USER_SESSION);
            User user = (User) attribute;
            bill = new Bill();
            bill.setId(id);
            bill.setBillCode(billCode);
            bill.setProductName(productName);
            bill.setProductUnit(productUnit);
            bill.setProductCount(count);
            bill.setTotalPrice(total);
            bill.setProviderId(_providerId);
            bill.setIsPayment(Payment);
            bill.setModifyDate(new Date());
            bill.setModifyBy(user.getId());
            BillServiceImpl billService = new BillServiceImpl();
            Boolean flag = billService.updateBill(bill);
            if (flag) {
                resp.sendRedirect("bill.do?method=query");
            } else {
                req.setAttribute(Constant.Message, "提交失败");
                req.getRequestDispatcher("bill.do?method=modify&billid="+id).forward(req, resp);
            }
        } catch (NumberFormatException | IOException e) {
            throw new RuntimeException(e);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }
    }
    public static void delBill(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String billid = req.getParameter("billid");
        Integer id = 0;
        if(!StringUtils.isNullOrEmpty(billid)){
            id = Integer.parseInt(billid);
        }
        PrintWriter writer = resp.getWriter();
        HashMap<String, Object> resultMap = new HashMap<>();
        if(id>0){
            BillServiceImpl billService = new BillServiceImpl();
            Boolean flag = billService.deleteBill(id);
            if(flag){
                resultMap.put("delResult","true");
            }else {
                resultMap.put("delResult","false");
            }
        }else {
            resultMap.put("delResult","notexist");
        }
        writer.println(JSONArray.toJSONString(resultMap));
        writer.flush();
    }
}
